from collections.abc import Iterable
g = (x for x in range(1,5))
print(g) # 是生成器，好处是不会将保存在内存中
print(isinstance(g,(Iterable))) # 是否是可迭代的
next(g)
print("hello world")
# 遍历之后，此时的游标已经指向最后了
for x in g:
    print(x)
# next(g) # 游标已经到了最后了，此时再调用next就报错StopIteration

print("--------------------------------------------------------------")
g2 = (x for x in range(2,10) if x %2 == 0) # 偶数
for x in g2:
    print(x)
# next(g2) # 此时会报错StopIteration，停止迭代

print("--------------------------------------------------------------")


# 使用函数创建生成器yield关键字
def fib(max):
    n = 0
    a = 0
    b = 1
    while n <max:
        yield b
        b = a+b
        a = b
        n+=1
    return "done"

# 返回生成器
g3 = fib(4)
print(g3)
for x in g3:
    print(x)

print("--------------------------------------------------------------")

# 使用函数创建生成器yield关键字
def fib2():
    a = 0
    b = 1
    while True:
        temp = yield b #yield无返回值
        b = a+b
        a = b
        print(temp)
    return "done"

# g4这是个无限的生成器,g4代表了自然界中所有的斐波那契数
g4 = fib2()
print(g4)
next(g4) # 执行到了第一个yield就返回，所以这里调用了四次next但是只打印了三次None
next(g4)
next(g4)
next(g4)


print("--------------------------------------------------------------")
print(g4.__next__()) #与next(g4)一样。游标出界一样会报错Iteration
print(g4.__next__()) 

print("--------------------------------------------------------------")
print(g4.send(None)) # 遍历的另一种方式,第一次调用必须传None，后面参数就随便传，参数个数为1，并且会将参数打印出来
print(g4.send(1))
print(g4.send(''))


print("--------------------------------------------------------------")
# 打印杨辉三角
def triangles():
    line = 0
    row = []
    while True:
        if(line == 0):
            row = [1]
            yield row
        elif(line == 1):
            row = [1,1]
            yield row
        else:
            row = [1] + [row[i]+row[i+1] for i in range(len(row)-1)]+ [1]
            yield row
        line+=1



# 期待输出:
# [1]
# [1, 1]
# [1, 2, 1]
# [1, 3, 3, 1]
# [1, 4, 6, 4, 1]
# [1, 5, 10, 10, 5, 1]
# [1, 6, 15, 20, 15, 6, 1]
# [1, 7, 21, 35, 35, 21, 7, 1]
# [1, 8, 28, 56, 70, 56, 28, 8, 1]
# [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
n = 0
results = []
for t in triangles():
    results.append(t)
    n = n + 1
    if n == 10:
        break

for t in results:
    print(t)

if results == [
    [1],
    [1, 1],
    [1, 2, 1],
    [1, 3, 3, 1],
    [1, 4, 6, 4, 1],
    [1, 5, 10, 10, 5, 1],
    [1, 6, 15, 20, 15, 6, 1],
    [1, 7, 21, 35, 35, 21, 7, 1],
    [1, 8, 28, 56, 70, 56, 28, 8, 1],
    [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
]:
    print('测试通过!')
else:
    print('测试失败!')
